package cn.usbtg.session.impl;

import cn.usbtg.session.BTGSession;
import cn.usbtg.session.BTGSessionDao;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.*;

/**
 * 基于db的session存储实现
 */
public class BTGDBSessionDao implements BTGSessionDao {

    protected static final Logger log = Logger.getLogger(BTGDBSessionDao.class);

    private BTGDBSessionDaoConfig config; //db配置

    public BTGDBSessionDao(BTGDBSessionDaoConfig sessionDBConfig) {
        this.config = sessionDBConfig;
    }

    @Override
    public void saveSession(BTGSession session) {
        try {
            Connection conn = this.config.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("insert into " + this.config.getTableName() + " (" + this.config.getSessionIdColumnName() + "," + this.config.getSessionObjColumnName() + ") values(?,?)");
            pstmt.setObject(1, session.getId());
            pstmt.setObject(2, session);
            pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            log.error(this, e);
        }
    }

    @Override
    public void deleteSession(String sessionId) {
        try {
            Connection conn = this.config.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("delete from " + this.config.getTableName() + " where " + this.config.getSessionIdColumnName() + " = ?");
            pstmt.setObject(1, sessionId);
            pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            log.error(this, e);
        }
    }

    @Override
    public BTGSession getSession(String sessionId) {
        BTGSession session = null;

        try {
            Connection conn = this.config.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("select " + this.config.getSessionObjColumnName() + " from " + this.config.getTableName() + " where " + this.config.getSessionIdColumnName() + " = ?");
            pstmt.setObject(1, sessionId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                ObjectInputStream oips = new ObjectInputStream(rs.getBinaryStream(1));
                session = (BTGSession) oips.readObject();
                oips.close();
            }
            rs.close();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            log.error(this, e);
        } catch (ClassNotFoundException e) {
            log.error(this, e);
        } catch (IOException e) {
            log.error(this, e);
        }

        return session;
    }

}
